#include <iostream>
#include <vector>

using namespace std;

//为什么这道题想到双指针法？
//只要遇到“原地修改”+“删除”/“保留”元素这类题型，第一反应就是双指针！

class Solution 
{
public:
	int removeElement(vector<int>& nums, int val) 
	{
		int slow = 0;	//慢指针指向有效元素存储位置的下一个位置，nums[0...slow-1]
		//快指针负责遍历整个数组
		
		for (size_t fast = 0; fast < nums.size(); fast++)	//nums.size()返回size_t(unsigned long long)无符号长整型
		{
			if (nums[fast] != val) 
			{
				nums[slow] = nums[fast];
				slow++;
			}
		}
		
		return slow;
	}
};

int main() 
{
	Solution sol;
	vector<int> nums = {0, 1, 2, 3, 4, 5, 2, 7, 2};
	int val;
	
	cout << "请输入要移除的值 val: ";
	cin >> val;
	
	int k = sol.removeElement(nums, val);
	
	cout << "移除后的有效长度 k = " << k << endl;
	cout << "前 k 个元素为: ";
	for (int i = 0; i < k; i++) 
	{
		cout << nums[i] << " ";
	}
	cout << endl;
	
	return 0;
}

